<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\Conf\Site;
use App\Models\Inf\Player;
use App\Models\Def\MainGamePlat;
use Dingo\Api\Routing\Helpers;
use Mockery\Exception;

class GameApiCheck
{
    use Helpers;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        //检查网站状态
        $siteUserName = request('username');

        if (isset($siteUserName)) {
            $siteNames=is_array($siteUserName)?$siteUserName:[$siteUserName];
            foreach ($siteNames as $siteName){
                $site = Site::where('username', $siteName)->first();
                if (empty($site)) {
                    return $this->response->error($siteName.':网站不存在或未启用', 422);
                }
            }


            if (!empty(\JWTAuth::parseToken()->getToken())) {
                try{
                    $payload = \JWTAuth::parseToken()->getPayload();
                    $key = $payload->get('key');
                }catch (Exception $exception){
                    report($exception);
                }

                $tokenSite=Site::where('token',$key)->first();
                if($tokenSite){
                    if(is_array($siteNames)){
                        if (!in_array($tokenSite->username,$siteNames)) {
                            return $this->response->error('网站key错误', 422);
                        }
                    }
                }else{
                    return $this->response->error('网站key错误,key 不存在', 422);
                }

            }

        }


        $platName = request('mainGamePlat');
        //检查平台
        if (isset($platName)) {
            $mainGamePlat = MainGamePlat::where('main_game_plat_name', $platName)->first();
            if (empty($mainGamePlat)) {
                return $this->response->error('游戏平台不存在或未启用', 422);
            }

            //玩家网站
            $accountUserName = request('accountUserName');
            if (isset($accountUserName)) {
                $player = Player::where([
                        ['main_game_plats_id', '=', $mainGamePlat->id],
                        ['username', '=', $accountUserName],
                    ]
                )->first();

                if ($player) {
                    $playerSite = $player->site()->first();
                }

                if (!isset($playerSite)) {
                    return $this->response->error('玩家不存在或玩家账号在此网站不存在', 422);
                }
            }
        }


        return $next($request);
    }
}
